package algorithms4g

import "fmt"

func init() {
	nums := []int{1, 3, 5, 7, 9}
	target := 6
	result := twoSum(nums, target)
	fmt.Println("两数之和-双for循环", result)
	result = twoSum2(nums, target)
	fmt.Println("两数之和，hash表", result)
}

/**
两数之和，暴力破解
*/
func twoSum2(nums []int, target int) []int {
	len := len(nums)
	for i := 0; i < len; i++ {
		for j := i + 1; j < len; j++ {
			if nums[i]+nums[j] == target {
				return []int{i, j}
			}
		}
	}
	return nil
}

/**
两数之和，hash表
*/
func twoSum(nums []int, target int) []int {
	hashMap := map[int]int{}
	for i, x := range nums {
		if v, ok := hashMap[target-x]; ok {
			return []int{v, i}
		}
		hashMap[x] = i
	}
	return nil
}
